<template>
  <div class="employees-container">
    <div class="app-container">
      <PageTools>
        <template #left>
          <span>总记录数:{{ total }}条</span>
        </template>
        <template #right>
          <el-button
            v-allow="'import_excel'"
            type="warning"
            size="small"
            @click="$router.push('/import')"
          >excel导入</el-button>
          <el-button
            v-allow="'export_excel'"
            type="danger"
            size="small"
            @click="exportExcel"
          >excel导出</el-button>
          <el-button type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </PageTools>

      <el-card style="margin-top: 10px;">
        <el-table
          border
          :data="list"
          :default-sort="{prop:'timeOfEntry', order: 'descending'}"
        >
          <el-table-column label="序号" width="50" type="index" />
          <el-table-column label="姓名" prop="username" />
          <!-- 显示员工的头像  -->
          <el-table-column label="员工头像" prop="username">
            <template #default="{row}">
              <img
                v-imgerror="require('@/assets/common/bigUserHeader.png')"
                :src="row.staffPhoto"
                alt=""
                style="width:50%"
                @click="showCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" sortable />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{row}">
              {{ formatData(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="hAssign(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page.sync="page"
            :page-size="size"
            layout=" prev, pager, next"
            :total="total"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <!-- 新增员工弹层  -->
      <el-dialog v-if="showDialog" title="新增员工" :visible.sync="showDialog">
        <addorEdit @success="hSucces" />
      </el-dialog>
      <el-dialog title="生成二维码图片" :visible.sync="showCodeDialog">
        <el-row type="flex" justify="center">
          <!-- 画布是用来显示二维码图片  -->
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <el-dialog title="分配角色" :visible.sync="AssignRoleDialog">
        <AssignRole
          v-if="AssignRoleDialog"
          :cur-id="curId"
          @success="AssignRoleDialog=false"
        />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import AssignRole from './assignRole.vue'
import addorEdit from '@/views/employees/empDialog.vue'
import { getEmployees, delEmployees } from '@/api/employees'
// 导入枚举文件获取里面的对象
import employeesEnum from '@/constant/employees'
// employeesEnum.hireType===>[{id:1,value:'正式'},{id:,value:'非正式'}]
// 把它转换为 {1:'正式',2:'非正式'}
// const hireType = {}
// employeesEnum.hireType.forEach(item => {
//   hireType[item.id] = item.value
// })
// [{id:1,value:'正式'},{id:2,value:'非正式'}]
// 数组.reduce(('累计和'，item，index)=>{},'默认值')
const hireType = employeesEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})

import QRCode from 'qrcode'
export default {
  components: {
    addorEdit,
    AssignRole
  },
  data() {
    return {
      AssignRoleDialog: false, // 控制权限分配的显示和隐藏
      showCodeDialog: false, // 控制二维码弹层的显示和隐藏
      list: [],
      page: 1,
      size: 5,
      total: 0,
      showDialog: false, // 控制新增员工弹层显示和隐藏
      curId: ''
    }
  },
  created() {
    this.loadEmployess()
  },
  methods: {
    // 点击分配角色获取id
    hAssign(id) {
      this.AssignRoleDialog = true
      this.curId = id
    },
    showCode(url) {
      if (url) {
        this.showCodeDialog = true // dom更新是异步的
        // 生成二维码图片
        this.$nextTick(() => {
          const canvas = this.$refs.myCanvas
          // 生成二维码图片
          QRCode.toCanvas(canvas, url)
        })
      } else {
        this.$message.error('请传入正确的图片')
      }
    },
    exportExcel() {
      // 1.发送到后台获取数据
      // 2.将获取到的数据进行格式化处理 tHeaer--->[表头],data--->[[],[]]
      const { tHeader, data } = this.transZhKeyToExcel(this.list)
      // 3.将格式化的数据写入到excel文件中
      // import('@/vendor/Export2Excel')  懒加载的方式导入一个模块， 返回值是一个promise实例
      import('@/vendor/Export2Excel').then(excel => {
        // excel指的模块对象，那么就可以使用这个模块对象去调用这个模块里面的函数或者访问变量   excel.函数名()
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.filename, // 文件名
          autoWidth: this.autoWidth, // 自动适应宽度
          bookType: this.bookType// 文件的类型
        })
      })
    },
    transZhKeyToExcel(list) {
      // 中引文的映射对象
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 1.生成表头
      const one = list[0]
      if (!one) return
      const tHeader = Object.keys(one).map(enkey => {
        return mapInfo[enkey]
      })
      // 2.生成表的内容 data
      const data = list.map(item => {
        return Object.values(item)
      })
      return { tHeader, data }
    },

    hDel(id) {
      console.log(id)
      this.$confirm('此操作将永久删除部门, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        // 做删除
        const res = await delEmployees(id)
        // console.log(res, 200)
        if (res.code === 10000) {
          this.$message.success(res.message)
          // 删除边界值的特殊处理
          if (this.list.length === 1) {
            this.page--
            if (this.page <= 0) {
              this.page = 1
            }
          }
          this.loadEmployess()
        }
        // this.doDel(id)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    hSucces() {
      this.total++
      // 计算最新的页码值
      const maxPage = Math.ceil(this.total / this.size)
      // 将页码值翻到最新的那一页
      this.page = maxPage
      this.loadEmployess()
      this.showDialog = false
    },
    handleCurrentChange(val) {
      this.page = val
      this.loadEmployess()
    },
    // 格式化数据的函数
    formatData(id) {
      // 目标将传过来的id  1 | 2 转化为 正式||非正式
      console.log(id, 'id')
      // 找到枚举文件里的hireType用id找到hireType数组里的id，
      // 用find方法返回id相等的对象，找到对象里的value
      // return employeesEnum.hireType.find(item => item.id === id).value
      return hireType[id] || '未知'
    },
    async loadEmployess() {
      try {
        const res = await getEmployees({ page: this.page, size: this.size })
        console.log(res, '获取列表成功')
        if (res.code !== 10000) return this.$message.error(res.message)
        // this.$message.success(res.message)
        this.list = res.data.rows
        this.total = res.data.total
      } catch (error) {
        this.$message.error(error)
      }
    }
  }
}
</script>
